import DbClient from 'ali-mysql-client'
// import { baseIp } from '../../../setting'
import * as Minio from 'minio'
import fs from 'fs'
import mime from 'mime'
import path from 'path'
import crypto from 'crypto'

const DB = new DbClient({
   host: 'localhost', //服务器地址，连接本机可以使用localhost或者127.0.0.1
   user: "root", //连接数据库的用户名
   password: "Silentwaver1.", //连接数据库的密码
   database: "pisiw", //数据库的名称
   port: 3306, //数据库端口号，默认3306，可以省略不写
})

const imgDir = '/apps/assets/image/setu'

const minioClient = new Minio.Client({
   endPoint: 'localhost',
   port: 9000,
   useSSL: false,
   accessKey: 'TzvUKRJqzoXRjogTAB3j',
   secretKey: '2wj6r02l1PyzYumQdyZOHaZOftrX9WDP63tIkBAy'
})


const items = fs.readdirSync(imgDir);
for (const item of items) {
   await setImage(item)
}
console.log('task over')

async function setImage(item) {
   const fType = path.extname(item)
   const oldName = path.basename(item)
   const contentType = mime.getType(item)

   const salt = crypto.randomBytes(5).toString('hex')
   const timestamp = new Date().getTime()
   const fname = timestamp + salt + fType;
   // console.log(oldName,fname,contentType)
   await minioClient.fPutObject('arts',
      fname,
      `${imgDir}/${oldName}`,
      { ContentType: contentType })
   await DB.insert('arts')
      .column('artName', fname)
      .column('uploadTime', new Date(timestamp))
      .column('uploader', 'sw')
      .column('path', fname)
      .execute()
   await setTimeout(() => { console.log(fname, 'handle next') }, 5000)

}